package com.taptech.doufu.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.AppUtil2;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.bean.SquareBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.services.DownloadWcsApkService;
import com.taptech.doufu.bean.GroupInfoBean;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;



public class SquareActivity extends DiaobaoBaseActivity implements HttpResponseListener
{

    ListView listView;
    List<SquareBean> list;
    SquareAdapter adapter;
    GroupInfoBean groupInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.square_layout);
        listView = (ListView) findViewById(R.id.square_list);
         listView.addHeaderView(getHeadView());
        list = new ArrayList<>();
        adapter = new SquareAdapter();
        listView.setAdapter(adapter);
        HomeMainServices.getInstance().loadSquarelList(this);
    }



    private View getHeadView()
    {
        View view = LayoutInflater.from(this).inflate(R.layout.square_layout_head, null);
        return view;
    }


    public void backOnClick(View view)
    {
        onBackPressed();
    }


    public void down(View view)
    {
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                ReceiveServerSocketData();
            }
        }).start();


    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 1001:
                   /* if (msg.getData().getString("content") != null)
                    {
                        editText.setText(msg.getData().getString("content"));
                    } else
                    {
                        editText.setText("null");
                    }*/
                    TTLog.i("TAG", "00000000000000000000000000000000000");
                    break;
            }
        }
    };

    public void ReceiveServerSocketData()
    {
        DatagramSocket socket;
        try
        {
            //实例化的端口号要和发送时的socket一致，否则收不到data
            // InetAddress ip = InetAddress.getLocalHost();
            InetAddress ip = InetAddress.getByName("192.168.0.108");
            socket = new DatagramSocket(502, ip);
            //socket = new DatagramSocket(502);
            byte data[] = new byte[4 * 1024];
            //参数一:要接受的data 参数二：data的长度
            DatagramPacket packet = new DatagramPacket(data, data.length);
            socket.receive(packet);
            //把接收到的data转换为String字符串
            String result = new String(packet.getData(), packet.getOffset(), packet.getLength());
            socket.close();//不使用了记得要关闭
            Message msg = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putString("content", result);
            msg.setData(bundle);
            msg.what = 1001;
            handler.sendMessage(msg);
        } catch (SocketException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    class SquareAdapter extends BaseAdapter
    {

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            SquareHolder squareHolder = null;
            if (convertView == null)
            {
                squareHolder = new SquareHolder();
                convertView = getLayoutInflater().inflate(R.layout.home_square_item, parent, false);
                squareHolder.logo = (ImageView) convertView.findViewById(R.id.square_item_logo);
                squareHolder.name = (TextView) convertView.findViewById(R.id.square_item_name);
                squareHolder.des = (TextView) convertView.findViewById(R.id.square_item_des);
                squareHolder.start_tv = (TextView) convertView.findViewById(R.id.start_tv);
                convertView.setTag(squareHolder);
            } else
            {
                squareHolder = (SquareHolder) convertView.getTag();
            }
            final String url = list.get(position).getUrl();
            final String name = list.get(position).getName();
            // TTTTLog.i("TAG", "position:" + position + "  getType:" + list.get(position).getType());
            if (list.get(position).getType().equals("22"))
            {
                //extraBean = list.get(position).getExtra();

                if (list.get(position).getExtra() != null && AppUtil2.isApplicationAvilible(SquareActivity.this, list.get(position).getExtra().getPkg_name()))
                {
                    squareHolder.start_tv.setText("打开");
                } else
                {
                    squareHolder.start_tv.setText("下载");
                }
                // squareHolder.start_tv.setOnClickListener(new ThisClickListenner(squareHolder.start_tv.getText().toString(), list.get(position).getExtra()));
            } else if (list.get(position).getType().equals("52"))//广告墙
            {
                squareHolder.start_tv.setText("进入");
            } else if (list.get(position).getType().equals("51")) //插屏广告
            {
                squareHolder.start_tv.setText("围观");
            } else if (list.get(position).getType().equals("53")) //游戏中心
            {
                squareHolder.start_tv.setText("围观");
            } else
            {
                squareHolder.start_tv.setText("开始");
            }
            squareHolder.start_tv.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    if (((TextView) view).getText().equals("下载"))
                    {
                        AppUtil2.downLoadApp(SquareActivity.this, list.get(position).getExtra());

                    } else if (((TextView) view).getText().equals("打开"))
                    {
                        AppUtil2.openApp(SquareActivity.this, list.get(position).getExtra().getPkg_name());
                    } else if (((TextView) view).getText().equals("开始"))
                    {
                        Intent intent = new Intent();
                        intent.setClass(SquareActivity.this, BrowseActivity.class);
                        intent.putExtra(Constant.URL, url);
                        intent.putExtra(Constant.TITLE, name);
                        startActivity(intent);
                    } else if (((TextView) view).getText().equals("围观"))
                    {
                        if (list.get(position).getType().equals("53"))
                        {
                            Intent intent = new Intent();
                            intent.setClass(SquareActivity.this, BrowseActivity.class);
                            intent.putExtra(Constant.URL, url);
                            intent.putExtra(Constant.TITLE, name);
                            intent.putExtra(Constant.AD_ID, list.get(position).getFollow_id());
                            startActivity(intent);
                        }
                    }
                }
            });
            convertView.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    if (list.get(position).getType().equals("52"))//广告墙
                    {
                    } else
                    {
                        Intent intent = new Intent();
                        intent.setClass(SquareActivity.this, BrowseActivity.class);
                        intent.putExtra(Constant.URL, url);
                        intent.putExtra(Constant.TITLE, name);
                        startActivity(intent);
                    }

                }
            });
            ImageManager.displayImage(squareHolder.logo, list.get(position).getIcon());
            //  }
            squareHolder.name.setText(list.get(position).getName());
            squareHolder.des.setText(list.get(position).getDescription());
            return convertView;
        }

        public class SquareHolder
        {
            ImageView logo;
            TextView name, des, start_tv;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {
        try
        {
            switch (handleType)
            {
                case HomeMainServices.HANDLE_TYPE_LOAD_SQUARE:
                    JSONArray squareArray = (JSONArray) response.getData();
                    if (response.getStatus() == 0)
                    {
                        list = DiaobaoUtil.jsonArray2BeanList(SquareBean.class, squareArray);
                        adapter.notifyDataSetChanged();
                    } else
                    {
                        UIUtil.toastMessage(SquareActivity.this, Constant.loadingFail);
                    }
                    break;
                case PersonalInfoService.HANDLE_HOME_GAME_CIRCLE:
                    if (response.getStatus() == 0)
                    {
                        groupInfoBean = new GroupInfoBean();
                        JSONObject data = (JSONObject) response.getData();
                        JSONObject community = data.getJSONObject("community");
                        groupInfoBean.setName(community.getString("name"));
                        groupInfoBean.setStatus(community.getString("status"));
                        groupInfoBean.setCommunity_id(community.getString("community_id"));
                        groupInfoBean.setCommunity_type(community.getString("community_type"));
                        groupInfoBean.setIcon_url(community.getString("icon_url"));
                        groupInfoBean.setIntroduce(community.getString("introduce"));
                        groupInfoBean.setMaster_name(community.getString("master_name"));
                        groupInfoBean.setMember_counts(community.getString("member_counts"));
                        groupInfoBean.setMaster_uid(community.getString("master_uid"));
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume()
    {
        adapter.notifyDataSetChanged();
        super.onResume();
    }
}
